package 力扣;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 示例 1：

 输入：numerator = 1, denominator = 2
 输出："0.5"
 示例 2：

 输入：numerator = 2, denominator = 1
 输出："2"
 示例 3：

 输入：numerator = 2, denominator = 3
 输出："0.(6)"
 示例 4：

 输入：numerator = 4, denominator = 333
 输出："0.(012)"
 示例 5：

 输入：numerator = 1, denominator = 5
 输出："0.2"

 */

public class _166分数到小数 {
    public String fractionToDecimal(int numerator, int denominator) {
        String res="";
        if(numerator==0)
            return "0";
        if(numerator < 0 ^ denominator < 0)
            res+="-";
        long dividend = Math.abs(Long.valueOf(numerator));
        long divisor = Math.abs(Long.valueOf(denominator));
        long num=dividend/divisor;
        long yushu=dividend%divisor;
        res+=String.valueOf(num);
        if(yushu!=0)
            res+=".";
        String str="";
        int flag=0;
        Map<String,Integer> map=new LinkedHashMap<>();
        while(yushu!=0&& flag==0){
            long shang=yushu*10/divisor;
            yushu=yushu*10%divisor;
            str=String.valueOf(shang)+"*"+String.valueOf(yushu);
            if(map.containsKey(str)){
                flag=1;
                map.put(str,2);
                break;
            }
            map.put(str,1);
        }
        for(String key:map.keySet()){
            String[] tmp=key.split("\\*");
            if(map.get(key)==2){
                res+="("+tmp[0];
            }
            else
                res+=tmp[0];
        }
        if(flag==1)
            res+=")";
        return res;

    }
}
